<template>
	<div>
		<!-- <el-dialog :title="title" v-model="dialogVisible" class="redius8" width="1200" center :before-close="handleClose"> -->
		<el-scrollbar style="height: 700px;">
			<el-form :model="form" ref="queryRef" :rules="rules" :inline="true" label-width="106">
				<div class="bgWhite radius8 pt25">
					<el-form-item label="客户姓名" prop="customerName">
						<el-input size="large" @focus="chooseCustomer" :disabled="userId == ''? false :true"
							v-model="form.customerName" style="width: 248px" placeholder="请填写" />
					</el-form-item>
					<el-form-item label="订单来源" prop="orderSource">
						<el-select
						 :disabled="userId == '' || !addOrderCustomerMes.opportunitySource ? false : true"
						 v-model="form.orderSource" placeholder="请选择" size="large" style="width: 248px;">
							<el-option v-for="dict in bus_source" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="业务经理" prop="businessManagerId">
						<el-select :disabled="userId == ''? false :true" v-model="form.businessManagerId" placeholder="请选择" size="large" style="width: 248px"
							ref="busRef" @change="businessManagerFunc">
							<el-option v-for="dict in teamOptions" :key="dict.userId" :label="dict.userName"
								:value="dict.userId" />
						</el-select>
					</el-form-item>
					<el-form-item label="付款类型" prop="paymentType">
						<el-select v-model="form.paymentType" placeholder="请选择" size="large" style="width: 248px;"
							@change="paymentTypeChange()">
							<el-option v-for="dict in bus_pay_type" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="付款方式" prop="paymentMethod">
						<el-select v-model="form.paymentMethod" placeholder="请选择" size="large" style="width: 248px;">
							<el-option v-for="dict in bus_pay_status" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="订单金额" prop="orderTotalAmount">
						<el-input size="large" type="number" v-model="form.orderTotalAmount" style="width: 248px" placeholder="选择商品后显示"
							@input="paymentTypeChange(1)" />
					</el-form-item>
					<el-form-item label="付款金额" prop="depositAmount">
						<el-input size="large" type="number" v-model="form.depositAmount" style="width: 248px" placeholder="请填写"
							:disabled="disabledAmount" @input="paymentTypeChange()" />
					</el-form-item>
					<el-form-item label="订单差值" prop="differenceAmount">
						<el-input size="large" disabled v-model="form.differenceAmount" style="width: 248px" placeholder="请填写"
							 />
					</el-form-item>
					<el-row>
						<el-col :span="24">
							<el-form-item label="付款备注" prop="remark" style="width: 570px;">
								<el-input v-model="form.remark" style="box-shadow: none;" show-word-limit :rows="5"
									type="textarea" placeholder="请输入备注信息" resize="none"
									:input-style="{background:'#F7F8FA',borderRaduis:'15px',boxShadow:'none'}" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="24">
							<el-form-item label="付款截图" prop="paymentUrl" style="width: 570px;">
								<el-upload v-if="form.paymentUrl == ''" 
								:limit='1'
								accept=".jpeg,.jpg,.png"
								name="file" class="avatar-uploader" :action="url" :headers="headers"
									:show-file-list="false" :on-success="handleAvatarSuccess"
									:before-upload="beforeAvatarUpload">
									<!-- <img v-if="form.paymentUrl" :src="form.paymentUrl"
										style="width: 110px;height: 110px;" /> -->
									<div>
										<el-icon class="avatar-uploader-icon">
											<Plus />
										</el-icon>
										<div class="fs12">上传图片</div>
									</div>
								</el-upload>
								<div class="relative" v-else>
									<el-image
									  class="radius8"
									  style="width: 110px; height: 110px"
									  :src="form.paymentUrl" 
									  :preview-src-list="[form.paymentUrl]">
									</el-image>
									<div 
									@click="form.paymentUrl = ''"
									class="absolute fs18 cursor" style="z-index: 1;width: 18px; height: 18px;top: -12px; right: -7px;border-radius: 50%;background-color: #fff;">
										<el-icon><CircleCloseFilled /></el-icon>
									</div>
								</div>	
							</el-form-item>
						</el-col>
					</el-row>
					<div class="flex col-center row-between plr30 pb10 mt10">
						<div>
							<span class="color-red">*</span>
							<span class="fb fs16 color333 mr20">关联商品</span>
							<div class="fs12 color-red mt6 flex col-center">
								<span>预估收益：{{revenue}} (订单提成)</span>
								<span>+{{dividePrice}} (溢价分成)</span>
								<span class="ml10 flex col-center cursor main-color fs14" @click="countPriceGoods()">
									点击预估订单收益
								</span>
							</div>
						</div>
						<el-form class="flex col-top row-between" :model="form" :inline="true">
							<el-button class="mt5" type="defaultBtn" @click="handleAdd(0)">添加商品</el-button>
						</el-form>
					</div>
					<div class="plr30 mt20">
						<el-table :data="form.goods" style="width: 100%;text-align: center;"
							:cell-style="{ textAlign: 'center','line-height':'54px'}"
							:header-cell-style="{ 'text-align': 'center','line-height':'54px','height':'54px!important'  }"
							:summary-method="getSummaries" show-summary>
							<el-table-column prop="commodityName" label="商品名称" width="120px" />
							<el-table-column prop="commodityCode" label="商品编码" width="100px" />
							<el-table-column prop="specificationId" label="商品规格" width="100px">
								<template v-slot="scope">
									<dict-tag :options="bus_product_specification_unit"
										:value="scope.row.specificationId" />
								</template>
							</el-table-column>
							<el-table-column label="库存单价" width="190">
								<template #default="scope">
									<el-select placeholder="请选择" size="large" style="width: 178px"
										v-model="scope.row.unitSinglePrice"
										@change="unitSinglePriceChange(0,scope.$index)">
										<el-option v-for="item in scope.row.countSelectPrice" :key="item.value"
											:label="item.label" :value="item.value" />
									</el-select>
								</template>
							</el-table-column>
							<el-table-column label="销售单价（元）">
								<template #default="scope">
									<!-- @blur="countOrderAmount(1)" -->
									<el-form-item :prop="'commodityList.' + scope.$index + '.unitPrice'"
										style="margin-right: 0;margin-top: 18px;">
										<el-input type="number" min="0" v-model="scope.row.unitPrice"
											style="width: 84px" size="large"
											@input="unitPriceChange(scope.row.unitPrice,scope.$index)" placeholder="请输入"
											 />
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="quantity" label="数量">
								<template #default="scope">
									<el-form-item :prop="'commodityList.' + scope.$index + '.quantity'"
										style="margin-right: 0;margin-top: 18px;">
										<el-input type="number" min="1" v-model="scope.row.quantity"
											style="width: 80px" size="large" @input="quantityChange(0,scope.$index)"
											placeholder="请输入" />
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="numberOfShippingBoxes" label="箱数量">
								<template v-slot="scope">
									<div>
										<el-input type="number" min="0" v-model="scope.row.numberOfShippingBoxes"
											style="width: 80px" @input="numberOfShippingBoxesChange(1,scope.$index)" size="large"
											placeholder="请输入" />
									</div>
								</template>
							</el-table-column>
							<el-table-column prop="date" label="总价（元）" width="120px">
								<template #default="scope">
									{{(scope.row.unitPrice*1*scope.row.quantity*1).toFixed(2)}}
								</template>
							</el-table-column>
							<el-table-column prop="commission" label="提成比率">
								<template v-slot="scope">
									<div>
										<el-input type="number" min="0" v-model="scope.row.commissionRatio"
											:disabled="isCommissionRatio == 'commissionRatio' ? false : true" style="width: 80px"  size="large"
											placeholder="请输入" />
									</div>
								</template>
							</el-table-column>
							<el-table-column fixed="right" label="操作" align="center" width="100px"
								class-name="small-padding fixed-width">
								<template #default="scope">
									<el-button link style="color: red!important;" type="primary"
										@click="delGoods(scope.$index)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>
					<div>
						<div class="flex col-center row-between plr30 mt30">
							<div class="flex col-center">
								<!-- <span class="color-red">*</span> -->
								<span class="fb fs16 color333 mr20">赠品管理</span>
							</div>
							<el-form class="" :model="form" :inline="true">
								<el-button class="mt5" type="defaultBtn" @click="handleAdd(1)">添加赠品</el-button>
							</el-form>
						</div>
						<div class="plr30 mt20 pb30">
							<el-table :data="form.gift" style="width: 100%"
								:cell-style="{ textAlign: 'center','line-height':'54px'}"
								:header-cell-style="{ 'text-align': 'center','line-height':'54px','height':'54px!important'  }">
								<el-table-column prop="commodityName" label="商品名称" width="120px" />
								<el-table-column prop="commodityCode" label="商品编码" width="100px" />
								<el-table-column prop="specificationId" label="商品规格" width="100px">
									<template v-slot="scope">
										<dict-tag :options="bus_product_specification_unit"
											:value="scope.row.specificationId" />
									</template>
								</el-table-column>
								<el-table-column label="库存单价" width="190">
									<template #default="scope">
										<el-select disabled placeholder="请选择" size="large" style="width: 178px"
											v-model="scope.row.unitSinglePrice"
											@change="unitSinglePriceChange(1,scope.$index)">
											<el-option v-for="item in scope.row.countSelectPrice" :key="item.value"
												:label="item.label" :value="item.value" />
										</el-select>
									</template>
								</el-table-column>
								<el-table-column label="销售单价（元）">
									<template #default="scope">	
										<el-input type="number" disabled min="0" v-model="scope.row.unitPrice"
											style="width: 113px" size="large"
											placeholder="请输入" />
									</template>
								</el-table-column>
								<!-- <el-table-column label="销售单价（元）" width="200px">
									<template #default="scope">
										<el-form-item :prop="'commodityList.' + scope.$index + '.unitPrice'"
											style="margin-right: 0;margin-top: 18px;">
											<el-input type="number" min="0" v-model="scope.row.unitPrice"
												style="width: 120px" size="large"
												@input="unitPriceChange1(scope.row.unitPrice,scope.$index)"
												 :min="scope.row.factoryPrice"
												placeholder="请输入" />
										</el-form-item>
									</template>
								</el-table-column> -->
								<el-table-column prop="quantity" label="数量" >
									<template #default="scope">
										<el-form-item :prop="'commodityList.' + scope.$index + '.quantity'"
											style="margin-right: 0;margin-top: 18px;">
											<el-input type="number" min="1" v-model="scope.row.quantity"
												style="width: 87px" size="large"
												@input="quantityChange1(1,scope.$index)" placeholder="请输入" />
										</el-form-item>
									</template>
								</el-table-column>
								<el-table-column prop="numberOfShippingBoxes" label="箱数量">
									<template v-slot="scope">
										<div>
											<el-input type="number" min="0" v-model="scope.row.numberOfShippingBoxes"
												@input="numberOfShippingBoxesChange(2,scope.$index)" size="large"
												placeholder="请输入" />
										</div>
									</template>
								</el-table-column>
								<el-table-column prop="date" label="总价（元）" width="120px">
									<template #default="scope">
										{{(scope.row.unitPrice*1*scope.row.quantity*1).toFixed(2)}}
									</template>
								</el-table-column>
								<el-table-column fixed="right" label="操作" align="center" width="100px"
									class-name="small-padding fixed-width">
									<template #default="scope">
										<el-button link style="color: red!important;" type="primary"
											@click="delGift(scope.$index)">删除</el-button>
									</template>
								</el-table-column>
							</el-table>
						</div>
					</div>
				</div>
				<div class="bgWhite radius8 pt20">
					<div class="fb fs16 color333 fs16 pl20 mb30">
						收货信息
					</div>
					<el-form-item label="收货人信息" prop="recipient">
						<el-input size="large" v-model="form.recipient" style="width: 248px;" placeholder="请填写" />
					</el-form-item>
					<el-form-item label="收货人手机号" prop="recipientPhone">
						<el-input size="large" v-model="form.recipientPhone" style="width: 248px;" placeholder="请填写" />
					</el-form-item>
					<el-form-item label="物流" prop="logisticsId">
						<el-select v-model="form.logisticsId" placeholder="请选择" size="large" style="width: 248px;" @change="logChange">
							<el-option v-for="dict in logListArr" :key="dict.id" :label="dict.logisticsCompany"
								:value="dict.id" />
						</el-select>
					</el-form-item>
					<!-- <el-form-item label="收货地址" prop="areaCode" style="margin-right: 15px;">
						<el-select v-model="form.areaCode" placeholder="请选择" size="large" style="width: 150px;">
							<el-option v-for="item in addressList" :key="item.code" :label="item.name"
								:value="item.code">
							</el-option>
						</el-select>
					</el-form-item> -->
					<el-form-item label="收货地址" prop="areaCodeAll">
						<el-cascader v-model="addressNode" ref="cascader" style="width:248px;" :props="address"
							@change="handleChangeAddress" size="large">
						</el-cascader>
					</el-form-item>
					<el-form-item label="详细收货地址" prop="shippingAddress1">
						<el-input size="large" v-model="form.shippingAddress1" style="width: 635px;"
							placeholder="请填写详细收货地址" />
					</el-form-item>

				</div>
				<div class="bgWhite radius8 pt20">
					<div class="fb fs16 color333 pb15 pl20">
						其他信息
					</div>
					<el-form-item label="领导审批" prop="documentType" label-width="100px">
						<el-radio-group v-model="form.documentType" style="width: 340px">
							<el-radio v-for="dict in bus_document_type" :key="dict.value" :label="dict.value"
								:value="dict.value" size="large">
								{{dict.label}}
							</el-radio>
						</el-radio-group>
					</el-form-item>
					<div>
						<el-form-item label="发货备注" prop="deliverGoodsRemark"  label-width="100px">
							<el-input v-model="form.deliverGoodsRemark" style="box-shadow: none;" show-word-limit 
								type="textarea" placeholder="请输入备注信息" resize="none" maxlength="200" rows="3"
								:input-style="{background:'#F7F8FA',borderRaduis:'15px',boxShadow:'none',width:'1032px'}" />
						</el-form-item>
					</div>
				</div>
			</el-form>
		</el-scrollbar>
		<div class="text-center mt25 pb30">
			<!-- || form.orderStatus == '1001' -->
			<el-button type="defaultBtn" style="height: 38px;" v-if="form.id == ''"
				@click.stop="orderSubmit('queryRef')">提交审批</el-button>
			<el-button type="operate" style="width: 88px;height: 38px;" v-if="form.id == ''"
				@click.stop="saveOrderDemo('queryRef')">保存草稿</el-button>
			<el-button type="defaultBtn" style="height: 38px;" v-if="form.id != ''"
				@click.stop="orderSubmit('queryRef')">编辑提交</el-button>
			<el-button type="operate" style="width: 88px;height: 38px;" @click="cancel">取消</el-button>
			<el-button type="operate" @click="previewFunc()" style="width: 88px;height: 38px;border: 1px solid red;color: red;">
				预览
			</el-button>
			
		</div>
		<!-- 客户弹窗 -->
		<customerList ref="customerDialog" @customerFunc="customerFunc"></customerList>
		<!-- 添加商品 -->
		<addGoodsList ref="goodsPop" @getGoods="selectGoods" :idArr="idsGoodsArr"></addGoodsList>
		<!-- 添加赠品 -->
		<addGiftList ref="giftPop" @getGift="selectGift" :idArr="idsGiftArr"></addGiftList>
		<!-- </el-dialog> -->
		<div class="pl20" style="color:  red;" v-if="form.isGrossProfitMarginShow">
			<span>毛利率：</span><span>{{form.orderGrossProfitRate}}%</span>
		</div>
		<!-- 预览界面 -->
		<previewPop ref="preview" :form="form"></previewPop>
	</div>
</template>

<script>
	import customerList from "@/components/customer/index.vue" //客户
	import addGoodsList from '@/components/addGoods/index.vue' //添加商品
	import addGiftList from '@/components/addGift/index.vue' //添加赠品
	import previewPop from './preview.vue' //预览界面
	import {
		getDivisions //省市区
	} from "@/api/business/opportunity";
	import {
		list 
	} from "@/api/business/rules_logistics";//物流
	import {
		getUserListData //查业务经理
	} from "@/api/business/teamOpportunity";
	import {
		getToken
	} from "@/utils/auth";
	let url = import.meta.env.VITE_APP_BASE_API + "/common/upload"
	import {
		getGoodsGroup, //查询商品组
	} from "@/api/business/product";
	import {
		fnRoyalties, //计算提成
		orderAdd, //提交订单
		orderDetail, //获取订单详情
		orderEdit, //编辑订单
		orderDemo, //保存草稿
		fnCommodity, //计算商品箱数
		conversion //获取商品折算价格
	} from "@/api/business/order";
	import {
		getCustomerDetail
	} from "@/api/business/customer";
	import {
		format
	} from "echarts";
	import {
		formProps
	} from "element-plus";
	export default {
		props: {
			//要创建订单的客户信息
			addOrderCustomerMes: {
				type: Object,
				default: res => {
					return {}
				}
			},
			isCommissionRatio:{
				type:String,
				default:''// 组长主管审批可变更提成比率
			}
		},
		components: {
			previewPop,//创建订单预览
			customerList,
			addGoodsList,
			addGiftList
		},
		data() {
			return {
				show: true,
				dialogVisible: false,
				title: '',
				headers: {
					Authorization: 'Bearer ' + getToken()
				},
				url: url,
				imageUrl: '',
				value: '',
				checked1: false,
				checked2: false,
				bus_source: this.useDict('bus_source').bus_source, //来源
				bus_pay_type: this.useDict('bus_pay_type').bus_pay_type, //类型
				bus_pay_status: this.useDict('bus_pay_status').bus_pay_status, //方式
				bus_product_specification_unit: this.useDict('bus_product_specification_unit')
					.bus_product_specification_unit, //瓶 套
				bus_goods_price_type: this.useDict('bus_goods_price_type').bus_goods_price_type, //
				bus_document_type: this.useDict('bus_document_type').bus_document_type, //文档单据
				teamOptions: [], //业务经理
				goodsId: [], //关联商品的id,
				userId: '', //从客户列表过来的创建订单
				commissionRate:true,//是否客编辑提成比率，默认不可编辑
				form: {
					id: '',
					orderSource: '', //订单来源
					customerId: '', //客户id
					customerName: '', //客户姓名
					businessManagerId: '', //业务经理id
					businessManager: '', //业务经理
					paymentType: '1002', //付款类型
					paymentMethod: '', //付款方式
					depositAmount: '', //付款金额
					orderTotalAmount: '', //订单总金额
					differenceAmount:'',//订单差值
					remark: '', //备注
					paymentUrl: '', //付款截图url
					recipient: '', //收货人
					recipientPhone: '', //收货人手机号
					addressName:'',
					shippingAddress:'',
					shippingAddress1: '', //收货地址
					logisticsId: '', //物流id
					logistics: '', //物流名称
					documentType: '1001', //文档单据类型
					priceType: '1001', //默认出厂价bus_goods_price_type 字典
					goods: [], //商品
					gift: [], //赠品
					areaCode: '', //省
					commodityList: [{
						type: '', //类型（0=商品，1=赠品）
						commodityId: '', //商品id
						commoditySpecification: '', //商品规格
						factoryPrice: '', //出厂价
						unitPrice: '', //销售单价（元）
						quantity: '1', //数量
						subtotal: '', //小计
						classifyId: '', //分类id
						commodityType: '', //产品类型正常品，试验品促销品
						commodityNumber: '', //商品编码
						productId: '', //关联产品id
						specificationId: '', //关联规格ID
						commodityName: '', //商品名称
						commodityCode: '', //商品Code码
						minUnit: '', //最小单位
						caseQuantity: '', //整件数量
						unitContent: '', //单位含量
						contentUnit: '', //含量单位（数据字典）
						mainImageUrl: '', //商品主图URL
						onlineUnitPrice: '', //线上拆箱单价
						caseUnitPrice: '', //整件单价
						tonPrice: '', //吨价
						numberOfShippingBoxes: '', //箱数量
					}] ,//订单商品信息
					deliverGoodsRemark:'',//发货备注
				},
				rules: {
					orderSource: [{
						required: true,
						message: '请选择订单来源',
						trigger: 'change'
					}, ],
					customerName: [{
						required: true,
						message: '请输入客户姓名',
						trigger: 'blur'
					}, ],
					paymentMethod:[
						{
							required: true,
							message: '请选择付款方式',
							trigger: 'change'
						},
					],
					orderTotalAmount: [{
						required: true,
						message: '请选择商品计算订单金额',
						trigger: 'blur'
					}],
					depositAmount: [{
						required: true,
						message: '请输入付款金额',
						trigger: 'blur'
					}],
					recipient: [{
						required: true,
						message: '请输入收货人',
						trigger: 'blur'
					}, ],
					recipientPhone: [{
							required: true,
							message: '请输入收货人手机号',
							trigger: 'blur'
						},
						{
							pattern: /^1[3-9]\d{9}$/,
							message: '手机号码格式不正确',
							trigger: 'blur'
						}
					],
					areaCodeAll: [{
						required: true,
						message: '请选择省市区',
						trigger: 'change'
					}, ],
					shippingAddress1: [{
						required: true,
						message: '请输入收货地址',
						trigger: 'blur'
					}, ],
					logisticsId: [{
						required: true,
						message: '请选择物流方式',
						trigger: 'change'
					}, ],
					documentType: [{
						required: true,
						message: '请选择文档单据',
						trigger: 'change'
					}, ],
					quantity: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}, ],
					unitPrice1: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}, ],
					quantity2: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}, ],
					unitPrice2: [{
						required: true,
						message: '请输入',
						trigger: 'blur'
					}, ]
				},
				disabledAmount: true, //付款金额不可编辑：详情 付款方式全款
				list: [{}],
				loading: false,
				yjPrice: 0, //溢价
				hjPrice: 0, //合计
				giftIds: [],
				getForm: '', //获取到的存储form
				addressNode: [],
				address: {
					lazy: true,
					lazyLoad(node, resolve) {
						setTimeout(() => {
							const nodes = [];
							// 构造查询条件
							let query = {
								id: node.level == 0 ? 0 : node.value,
								level: node.level + 1,
								type: 'provinces',
								pCode: node.value,
								pageNum: 1,
								pageSize: 5000
							}
							if (query.level == 2) {
								query.type = 'cities';
								// form.customerAddress = node.label;
							}
							if (query.level == 3) {
								query.type = 'areas';
							}
							if (query.level == 4) {
								query.type = 'streets';
							}
							//查询接口
							getDivisions(query, query.type).then(res => {
								res.rows.map((item) => {
									let obj = {
										value: item.code,
										label: item.name,
										pCode: item.pCode,
										leaf: query.level >= 3
										//leaf: item.hasChildren // 节点级别，如果没有子节点就停止查询
									}
									nodes.push(obj);
								})
								//重新加载节点
				
								resolve(nodes);
							})
						}, 100);
					}
				},
				addressList: [], //地址列表数组
				revenue: 0, //预估收益
				dividePrice: 0, //溢价分成
				idsGoodsArr: [], //已经选择的商品id
				idsGiftArr: [], //已选择赠品id
				propVal: {
					customerId: '',
					customerName: ''
				},
				isCanGift: false, //是否可以添加赠品
				obj: {},
				isCanGiftFunc:'',
				logListArr:''//物流
			}
		},
		watch: {
			// addOrderCustomerMes(val) {
			// 	this.form.businessManagerId = this.addOrderCustomerMes.businessManagerId
			// 	this.form.businessManagerName = this.addOrderCustomerMes.businessManagerName
			// 	this.form.customerId = this.addOrderCustomerMes.customerId
			// 	this.form.customerName = this.addOrderCustomerMes.customerName
			// 	this.form.opportunitySource = this.addOrderCustomerMes.opportunitySource
			// 	this.userId = this.addOrderCustomerMes.customerId
			// 	this.propVal = this.addOrderCustomerMes
			// 	console.log(this.propVal,'dkdkdkdkddkkd')
			// }
		},
		created() {
			this.getUserList()
			// 获取地址
			this.getAddress()
		},
		methods: {
			// 预览
			previewFunc(){
				this.form.shippingAddress = this.form.addressName + ' ' + this.form.shippingAddress1
				this.form.commodityList = this.form.goods.concat(this.form.gift)
				this.$refs.preview.open()
			},
			// 取消
			cancel(){
				this.$emit('handleClose')
			},
			// 选择地址
			handleChangeAddress(e) {
				let nodesObj = this.$refs["cascader"].getCheckedNodes()[0].pathLabels;
				this.form.areaCode = this.addressNode[0]
				console.log(this.addressNode,'addressNode')
				this.form.addressName = nodesObj[0]+nodesObj[1]+nodesObj[2]
				// +nodesObj[3] //省市区街道
				this.form.areaCodeAll = this.addressNode.join(',')
				
				
			},
			handleSubmit(event) {
				event.preventDefault(); // 阻止表单的默认提交行为
			},
			//付款类型更改
			paymentTypeChange(num) {
				if(num == 1){
					//订单差值
					this.form.differenceAmount = Math.abs(this.form.orderTotalAmount*1 - this.hjPrice*1).toFixed(2)
				}
				//定金
				if (this.form.paymentType == '1002') {
					//全款 付款金额 = 订单金额
					this.form.depositAmount = this.form.orderTotalAmount
					this.disabledAmount = true
				} else {
					this.disabledAmount = false
				}
				
				this.$forceUpdate()
			},
			//库存单件// 计算商品箱数
			unitSinglePriceChange(num, index, count) {
				let arrList = []
				if (num == 0) {
					arrList = this.form.goods
				} else if (num == 1) {
					arrList = this.form.gift
				}
				if(count){
					arrList[index].numberOfShippingBoxes = (arrList[index].quantity * 1 / arrList[index].conQuantity
						.toBox * 1).toFixed(3)
				}else{
					// for (let index in arrList) {
						if (arrList[index].unitSinglePrice == 0 && arrList[index].conQuantity) {
							arrList[index].unitPrice = arrList[index].conPrice.unitPrice
							arrList[index].factoryPrice = arrList[index].conPrice.unitPrice
						} else if (arrList[index].unitSinglePrice == 1 && arrList[index].conQuantity) {
							arrList[index].unitPrice = arrList[index].conPrice.boxConversionUnitPrice
							arrList[index].factoryPrice = arrList[index].conPrice.boxConversionUnitPrice
							// if(num == 0){
							// 	arrList[index].numberOfShippingBoxes = arrList[index].quantity
							// }
						} else if (arrList[index].unitSinglePrice == 2 && arrList[index].conQuantity) {
							arrList[index].unitPrice = arrList[index].conPrice.tonConversionUnitPrice
							arrList[index].factoryPrice = arrList[index].conPrice.tonConversionUnitPrice
							// if(num == 0){
							// 	arrList[index].numberOfShippingBoxes = (arrList[index].quantity * 1 * arrList[index].conQuantity.toTon * 1).toFixed(2)
							// }
						}
					// }
				}
				
				// if (num == 0 && count && arrList[index].unitSinglePrice != 1 || num == 1 && count && arrList[index].unitSinglePrice != 0) {
				// 	arrList[index].numberOfShippingBoxes = (arrList[index].quantity * 1 / arrList[index].conQuantity
				// 		.toBox * 1).toFixed(2)
				// }else{
				// 	arrList[index].numberOfShippingBoxes = arrList[index].quantity * 1
				// }
				
				// }
				this.countPrice()
				this.$forceUpdate()
			},
			//箱数量改变
			numberOfShippingBoxesChange(num, index) {
				let arrList = []
				if (num == 1) {
					arrList = this.form.goods
				} else {
					arrList = this.form.gift
				}
				// for (let index in arrList) {
				// if (arrList[index].unitSinglePrice == 0) {
				// 	arrList[index].unitPrice = arrList[index].factoryPrice
				// 	// 箱价conQuantity tobox
				// } else if (arrList[index].unitSinglePrice == 1) {
				// 	arrList[index].unitPrice = arrList[index].boxConversionUnitPrice
				// 	// arrList[index].numberOfShippingBoxes = arrList[index].quantity
				// } else if (arrList[index].unitSinglePrice == 2) {
				// 	arrList[index].unitPrice = arrList[index].tonConversionUnitPrice
				// 	// arrList[index].quantity = (arrList[index].numberOfShippingBoxes * 1 / arrList[index].conQuantity.toTon * 1).toFixed(2)
				// }
				// console.log(num,arrList[index].unitSinglePrice,'arrList[index].unitSinglePrice')
					// if (num == 1 && arrList[index].unitSinglePrice != 1 || num == 2 && arrList[index].unitSinglePrice != 0) {
					// 	arrList[index].quantity = (arrList[index].numberOfShippingBoxes * 1 * arrList[index].conQuantity.toBox * 1)
					// 		.toFixed(2)
					// }else{
					// 	arrList[index].quantity = arrList[index].numberOfShippingBoxes * 1
					// }
					arrList[index].quantity = (arrList[index].numberOfShippingBoxes * 1 * arrList[index].conQuantity.toBox * 1)
						.toFixed(2)
				// }
				this.countPrice()
			},
			handleClose() {
				this.dialogVisible = false
			},
			open(num, disabled) {
				if (this.reset()) {
					if (num == '') {
						this.title = '新建订单'
						if(JSON.stringify(this.addOrderCustomerMes) != '{}'){
							this.form.businessManagerId = this.addOrderCustomerMes.businessManagerId
							this.form.businessManager = this.addOrderCustomerMes.businessManagerName
							this.form.customerId = this.addOrderCustomerMes.customerId
							this.form.customerName = this.addOrderCustomerMes.customerName
							this.form.orderSource = this.addOrderCustomerMes.opportunitySource
							this.form.recipient = this.addOrderCustomerMes.customerName
							this.form.recipientPhone = this.addOrderCustomerMes.phoneNumber
							this.form.areaCode = this.addOrderCustomerMes.localProvince
							this.addressNode = [this.addOrderCustomerMes.localProvince,this.addOrderCustomerMes.localCity,this.addOrderCustomerMes.localCounty],
							this.form.addressName = this.addOrderCustomerMes.localProvinceName+this.addOrderCustomerMes.localCityName+this.addOrderCustomerMes.localCountyName //省市区街道
							this.form.shippingAddress1 = this.addOrderCustomerMes.shippingAddress
							this.form.areaCodeAll = this.addressNode.join(',')
							this.userId = this.addOrderCustomerMes.customerId
						}
						// console.log(this.addOrderCustomerMes,'userId')
					} else if (num != '' && !disabled) {
						this.title = '编辑订单'
						this.form.id = num
						this.getDetail()
					}
					this.dialogVisible = true
					if(this.addressNode && this.addressNode.length == 0) {
						console.log(this.$refs.cascader.$refs,'this.$refs.cascader')
						this.$refs.cascader.$refs.panel.checkedValue = []; // 清空选中值
						this.$refs.cascader.$refs.panel.clearCheckedNodes(); // 清空级联选择器选中状态
						this.$refs.cascader.$refs.panel.activePath = []; // 清除高亮
						this.$refs.cascader.$refs.panel.syncActivePath(); // 初始化（只展示一级节点）
					}
				}
			},
			getAddress() {
				let query = {
					id: 0,
					level: 1,
					type: 'provinces',
					pCode: '',
					pageNum: 1,
					pageSize: 5000
				}
				getDivisions(query, query.type).then(res => {
					this.addressList = res.rows
					this.getDivisionsList()
				})
			},
			// 物流
			getDivisionsList(){
				let data = {
					pageNum: 1,
					pageSize: 200,
					level: 2,
					channel: "1001",
					type: "provinces"
				}
				list(data).then((response) => {
					this.logListArr = response.rows;
				});
			},
			// 物流切换
			logChange(e){
				for(let key in this.logListArr){
					if(this.logListArr[key].id == e){
						this.form.logistics = this.logListArr[key].logisticsCompany
					}
				}
			},
			//获取订单详情
			getDetail() {
				orderDetail(this.form.id).then(res => {
					this.form = res.data
					this.addressNode = this.form.areaCodeAll?this.form.areaCodeAll.split(','):[]
					if(this.addressNode.length == 4){
						this.addressNode.splice(3,1)
					}
					this.form.addressName = this.form.shippingAddress.split(' ')[0]
					this.form.shippingAddress1 = this.form.shippingAddress.split(' ')[1]
					// console.log(this.form.shippingAddress1,'this.form.shippingAddress1')
					let goods = []
					let gift = []
					let ids = []
					for (let key in this.form.commodityList) {
						ids.push(this.form.commodityList[key].commodityId)
						// this.form.commodityList[key].countSelectPrice = [{
						// 		value: 0,
						// 		label: '单价：' + this.form.commodityList[key].factoryPrice + '元'
						// 	},
						// 	{
						// 		value: 1,
						// 		label: '箱价折算单价：' + this.form.commodityList[key].boxConversionUnitPrice + '元'
						// 	},
						// 	{
						// 		value: 2,
						// 		label: '吨价折算单价：' + this.form.commodityList[key].tonConversionUnitPrice + '元'
						// 	}
						// ]
						this.form.commodityList[key].unitSinglePrice = this.form.commodityList[key]
							.unitSinglePrice * 1
						if (this.form.commodityList[key].type == 0) {
							goods.push(this.form.commodityList[key])
						} else {
							gift.push(this.form.commodityList[key])
						}
					}

					//订单
					// this.conversion(ids)
					this.form.goods = goods
					this.form.gift = gift
					this.conversion(ids.join(','), 3)
					if (this.form.gift.length > 0) {
						this.isCanGift = true
					}
					// this.getChoose()
					this.$forceUpdate()
				})
			},
			// 计算商品折算价格
			conversion(ids, num) {
				let data = {
					ids: ids
				}
				conversion(data).then(res => {
					
					let data_ = res.data
					let nestedObjects = []
					let arrList = []
					if (num == 0) {
						arrList = this.form.goods
					} else if (num == 1) {
						arrList = this.form.gift
					} else {
						arrList = this.form.goods.concat(this.form.gift)
					}
					
					let getIds = ids.split(',')
					for (const item of data_) {
						this.obj[Object.keys(item)] = Object.values(item)[0]
					}
					if(num == 0 || num == 1){
						for (let key in arrList) {
							for(let m in getIds){
								if(getIds[m] == arrList[key].commodityId){
									if(arrList[key].type == 0){
										arrList[key].factoryPrice = this.obj[arrList[key].commodityId].price.unitPrice
										arrList[key].countSelectPrice = [{
													value: 0,
													label: '单价：' + this.obj[arrList[key].commodityId].price.unitPrice + '元'
												},
												{
													value: 1,
													label: '折箱单价：' + this.obj[arrList[key].commodityId].price
														.boxConversionUnitPrice + '元'
												},
												{
													value: 2,
													label: '折吨单价：' + this.obj[arrList[key].commodityId].price.tonConversionUnitPrice + '元'
												}
											]
											 arrList[key].unitPrice = this.obj[arrList[key].commodityId].price.unitPrice
									}else{	
										arrList[key].factoryPrice = this.obj[arrList[key].commodityId].price.boxConversionUnitPrice
										arrList[key].countSelectPrice = [
												{
													value: 0,
													label: '折箱单价：' + this.obj[arrList[key].commodityId].price.boxConversionUnitPrice + '元'
												}
											]
											 arrList[key].unitPrice = 0
									}
							
									arrList[key].conPrice = this.obj[arrList[key].commodityId].price
									arrList[key].conQuantity = this.obj[arrList[key].commodityId].quantity
									arrList[key].numberOfShippingBoxes = (arrList[key].quantity * 1 / this.obj[arrList[key].commodityId].quantity.toBox * 1).toFixed(3)
								}
							}		
						}
					}else if (num == 3) {
						for (let index in arrList) {
							if(arrList[index].type == 0){
								arrList[index].countSelectPrice = [{
										value: 0,
										label: '单价：' + this.obj[arrList[index].commodityId].price.unitPrice + '元'
									},
									{
										value: 1,
										label: '折箱单价：' + this.obj[arrList[index].commodityId].price.boxConversionUnitPrice + '元'
									},
									{
										value: 2,
										label: '折吨单价：' + this.obj[arrList[index].commodityId].price.tonConversionUnitPrice + '元'
									}
								]
							}else{
								arrList[index].countSelectPrice = [
									{
										value: 0,
										label: '折箱单价：' + this.obj[arrList[index].commodityId].price.boxConversionUnitPrice + '元'
									}
								]
							}
							arrList[index].conPrice = this.obj[arrList[index].commodityId].price
							arrList[index].conQuantity = this.obj[arrList[index].commodityId].quantity
							arrList[index].numberOfShippingBoxes = (arrList[index].quantity * 1 / this.obj[arrList[index].commodityId].quantity.toBox * 1).toFixed(3)
						}
					}
					this.countPrice(num)
					this.$forceUpdate()
				})
			},
			// 关联客户
			chooseCustomer() {
				this.$refs.customerDialog.open()
			},
			//获取选中的客户信息
			customerFunc(e) {
				console.log(e,'e=====')
				this.form.customerId = e.id
				this.form.customerName = e.name
				this.form.businessManagerId = e.businessManagerId
				this.form.businessManager = e.businessManagerName
				this.form.orderSource = e.opportunitySource
				this.form.recipient = e.name
				this.form.recipientPhone = e.phoneNumber
				this.form.areaCode = e.localProvince
				this.addressNode = [e.localProvince,e.localCity,e.localCounty]
				this.form.addressName = e.localProvinceName+e.localCityName+e.localCountyName //省市区街道
				this.form.shippingAddress1 = e.shippingAddress
				this.form.areaCodeAll = this.addressNode.join(',')
				console.log(this.form.areaCodeAll,'this.form.areaCodeAll')
			},
			// 获取业务经理
			getUserList() {
				//获取自己和同部门的用户信息
				getUserListData().then(response => {
					this.teamOptions = response.data;
				});
			},
			//选择业务经理
			businessManagerFunc(value) {
				let item = this.teamOptions.find((item) => {
					return item.userId === value
				})
				// console.log(item,'item===')
				this.form.businessManager = item.userName
				this.form.businessManagerId = item.userId
			},
			// 付款截图
			handleAvatarSuccess(e) {
				this.form.paymentUrl = e.url
			},
			beforeAvatarUpload(e) {},
			//选中的商品
			selectGoods(e) {
				let getValue 
				for(let key in this.form.goods){
					for(let j in e){
						if(this.form.goods[key].commodityId == e[j]){
							e.splice(j,1)
						}
					}
				}
				getValue = e
				this.getGoodsGroupList(e, 0)
			},
			// 关联商品查询
			getGoodsGroupList(ids, num) {
				// num:0商品  1赠品
				let deptId = JSON.parse(localStorage.getItem('user')).deptId
				let queryParams = {
					deptId: deptId
				}
				getGoodsGroup(ids, queryParams).then((response) => {
					let selectList = response.data
					this.goodsHandle(selectList, num, ids)
				})
			},
			//商品信息处理
			goodsHandle(selectList, num, ids) {
				if (selectList.length > 0) {
					let arr = []
					for (let i in selectList) {
						let item = {
							type: num, //类型（0=商品，1=赠品）
							commodityId: selectList[i].id, //商品id
							commoditySpecification: selectList[i].specificationId, //商品规格
							factoryPrice: selectList[i].offlinePrices[0].factoryPrice, //出厂价
							unitPrice: num == 0 ? selectList[i].offlinePrices[0].onlineUnitPrice : 0, //销售单价（元）
							quantity: '1', //数量
							subtotal: '', //小计
							classifyId: selectList[i].classifyId, //分类id
							commodityType: selectList[i].commodityType, //产品类型正常品，试验品促销品
							commodityNumber: selectList[i].commodityNumber, //商品编码
							productId: selectList[i].productId, //关联产品id
							specificationId: selectList[i].specificationId, //关联规格ID
							commodityName: selectList[i].commodityName, //商品名称
							commodityCode: selectList[i].commodityCode, //商品Code码
							minUnit: selectList[i].minUnit, //最小单位
							caseQuantity: selectList[i].caseQuantity, //整件数量
							unitContent: selectList[i].unitContent, //单位含量
							contentUnit: selectList[i].contentUnit, //含量单位（数据字典）
							mainImageUrl: selectList[i].mainImageUrl, //商品主图URL
							onlineUnitPrice: selectList[i].onlineUnitPrice, //线上拆箱单价
							caseUnitPrice: selectList[i].caseUnitPrice, //整件单价
							tonPrice: selectList[i].tonPrice, //吨价
							numberOfShippingBoxes: selectList[i].numberOfShippingBoxes, //箱数量
							boxConversionUnitPrice: selectList[i].boxConversionUnitPrice,
							tonConversionUnitPrice: selectList[i].tonConversionUnitPrice,
							commissionRatio:selectList[i].commission,//提成比率
							unitSinglePrice: 0
						}
						arr.push(item)
					}
					if (num == 0) {
						for (let k in this.form.goods) {
							for (let j in arr) {
								if (this.form.goods[k].commodityId == arr[j].commodityId) {
									arr.splice(j, 1)
								}
							}
						}
						this.form.goods = this.form.goods.concat(arr)
						this.conversion(ids.join(','), 0)
					} else {
						for (let k in this.form.gift) {
							for (let j in arr) {
								if (this.form.gift[k].commodityId == arr[j].commodityId) {
									arr.splice(j, 1)
								}
							}
						}
						this.form.gift = this.form.gift.concat(arr)
						this.conversion(ids.join(','), 1)
					}
					this.$forceUpdate()
				}
				
			},
			// 根据传入的关联商品数组,计算箱价和销售单价
			countListSinglePrice(arrList) {
				for (let index in arrList) {
					//1
					if (arrList[index].unitSinglePrice == 0 && arrList[index].conQuantity) {
						arrList[index].unitPrice = arrList[index].factoryPrice
						// arrList[index].numberOfShippingBoxes = (arrList[index].quantity * 1 / arrList[index].conQuantity
						// 	.toBox * 1).toFixed(2)

					} else if (arrList[index].unitSinglePrice == 1 && arrList[index].conQuantity) {
						arrList[index].unitPrice = arrList[index].boxConversionUnitPrice
						// arrList[index].numberOfShippingBoxes = arrList[index].quantity
					} else if (arrList[index].unitSinglePrice == 2 && arrList[index].conQuantity) {
						arrList[index].unitPrice = arrList[index].tonConversionUnitPrice
						// arrList[index].numberOfShippingBoxes = (arrList[index].quantity * 1 * arrList[index].conQuantity
						// 	.toTon * 1).toFixed(2)
					}
					arrList[index].numberOfShippingBoxes = (arrList[index].quantity * 1 / arrList[index].conQuantity
						.toBox * 1).toFixed(2)
				}
				this.$forceUpdate()
			},
			// 计算订单金额
			countOrderAmount(num) {
				let price = 0
				if (num == 2) {
					for (let key in this.form.gift) {
						//库存单价
						if (this.form.gift[key].unitSinglePrice == 0 && this.form.gift[key].unitPrice * 1 < this.form.gift[
								key].conPrice.unitPrice * 1) {
							this.form.gift[key].unitPrice = ''
							this.$modal.msgError('销售单价不得低于库存单价')
							return false;
						} else if (this.form.gift[key].unitSinglePrice == 1 && this.form.gift[key].unitPrice * 1 < this
							.form.gift[key].conPrice.boxConversionUnitPrice * 1) {
							this.form.gift[key].unitPrice = ''
							this.$modal.msgError('销售单价不得低于库存单价')
							return false;
						} else if (this.form.gift[key].unitSinglePrice == 2 && this.form.gift[key].unitPrice * 1 < this
							.form.gift[key].conPrice.tonConversionUnitPrice * 1) {
							this.form.gift[key].unitPrice = ''
							this.$modal.msgError('销售单价不得低于库存单价')
							return false;
						}
					}
				} else {
					// console.log(this.form.goods, '9d9s9a9f9af')
					for (let key in this.form.goods) {
						// price+=this.form.goods[key].unitPrice*1*this.form.goods[key].quantity*1
						if (this.form.goods[key].unitSinglePrice == 0 && this.form.goods[key].unitPrice * 1 < this.form
							.goods[key].conPrice.unitPrice * 1) {
							this.form.goods[key].unitPrice = ''
							this.$modal.msgError('销售单价不得低于库存单价')
							return false;
						} else if (this.form.goods[key].unitSinglePrice == 1 && this.form.goods[key].unitPrice * 1 < this
							.form.goods[key].conPrice.boxConversionUnitPrice * 1) {
							this.form.goods[key].unitPrice = ''
							this.$modal.msgError('销售单价不得低于库存单价')
							return false;
						} else if (this.form.goods[key].unitSinglePrice == 2 && this.form.goods[key].unitPrice * 1 < this
							.form.goods[key].conPrice.tonConversionUnitPrice * 1) {
							this.form.goods[key].unitPrice = ''
							this.$modal.msgError('销售单价不得低于库存单价')
							return false;
						}
					}
					// this.form.orderTotalAmount = price
				}
				this.$forceUpdate()
			},
			//添加商品----最后一行自定义
			getSummaries(param) {
				const {
					columns,
					data
				} = param;
				const sums = [];
				columns.forEach((column, index) => {
					if (index === 3) {
						sums[index] = '溢价金额：' + (this.yjPrice * 1).toFixed(2);
						return;
					} else if (index == 7) {
						sums[index] = '合计：' + (this.hjPrice * 1).toFixed(2);
					}
				});
				return sums;
			},
			// 添加商品 / 赠品
			handleAdd(num) {
				if (num == 0) {
					let arr = []
					if (this.form.goods.length > 0) {
						for (let key in this.form.goods) {
							arr.push(this.form.goods[key].commodityId)
						}
					} else {
						arr = []
					}
					this.idsGoodsArr = arr
					this.$refs.goodsPop.open()
				} else {
					let arr1 = []
					if (this.form.gift.length > 0) {
						for (let key in this.form.gift) {
							arr1.push(this.form.gift[key].commodityId)
						}
					} else {
						arr1 = []
					}
					this.idsGiftArr = arr1
					this.$refs.giftPop.open()
				}
			},
			// 关联商品价格联动
			unitPriceChange(value, index) {
				this.form.goods[index].unitPrice = value
				//选择
				let price = 0
				for (let key in this.form.goods) {
					if (this.form.goods[key].unitSinglePrice == 0) {
						price += (this.form.goods[key].unitPrice * 1 - this.form.goods[key].factoryPrice * 1)*this.form.goods[key].quantity*1
					}
				}
				this.yjPrice = price
				this.countPrice(1)
			},
			// 失去焦点判断销售价是否小于出厂价
			blurUnitPrice(value, index) {
				if (value && value * 1 < this.form.goods[index].factoryPrice * 1) {
					this.$modal.msgError('价格不得低于出厂价')
					this.form.goods[index].unitPrice = ''
				}
			},
			//关联商品数量联动
			quantityChange(num, index) {
				this.countPrice()
				this.unitSinglePriceChange(num, index, 1)
			},
			//赠品数量联动
			quantityChange1(num, index) {
				this.unitSinglePriceChange(num, index,1)
			},
			// 关联商品计算溢价/合计
			countPrice(num) {
				// console.log(this.form.goods,'this.form.goods')
				// 计算溢价
				let yjPrice = 0
				let total = 0 //总价
				for (let key in this.form.goods) {
					this.form.goods[key].subtotal = this.form.goods[key].unitPrice * 1 * this.form.goods[key].quantity * 1
					total += (this.form.goods[key].unitPrice * 1 * this.form.goods[key].quantity * 1)
					if(this.form.goods[key].unitSinglePrice == 0){
						yjPrice += (this.form.goods[key].unitPrice * 1 - this.form.goods[key].conPrice.unitPrice * 1)*this.form.goods[key].quantity*1
					}else if(this.form.goods[key].unitSinglePrice == 1){
						yjPrice += (this.form.goods[key].unitPrice * 1 - this.form.goods[key].conPrice.boxConversionUnitPrice * 1)*this.form.goods[key].quantity*1
					}else if(this.form.goods[key].unitSinglePrice == 2){
						yjPrice += (this.form.goods[key].unitPrice * 1 - this.form.goods[key].conPrice.tonConversionUnitPrice * 1)*this.form.goods[key].quantity*1
					}
				}
				this.yjPrice = yjPrice
				this.hjPrice = total.toFixed(2)
				if (this.form.paymentType == '1001') {
					this.disabledAmount = false
				} else {
					this.disabledAmount = true
					//3：详情，读取接口返回，不做计算
					if(num != 3){
						// 付款金额
						this.form.depositAmount = this.hjPrice
					}
				}
				//3：详情，读取接口返回，不做计算
				if(num != 3){
					//订单金额
					this.form.orderTotalAmount = total.toFixed(2)
					//订单差值
					this.form.differenceAmount = Math.abs(this.form.orderTotalAmount*1 -  total*1).toFixed(2)
				}
				this.$forceUpdate()
			},
			//删除关联商品
			delGoods(index) {
				this.form.goods.splice(index, 1)
				if (this.form.goods.length == 0) {
					this.revenue = 0
					this.dividePrice = 0
				}
				this.countPrice()
			},
			//删除赠品
			delGift(index) {
				this.form.gift.splice(index, 1)
			},
			// 赠品价格联动
			unitPriceChange1(value, index) {
				this.form.gift[index].unitPrice = value
				this.form.gift[index].subtotal = this.form.gift[index].unitPrice * 1 * this.form.gift[index].quantity * 1
			},
			//预估收益
			countPriceGoods() {
				//没有选择商品切换
				if (this.form.goods.length == 0) {
					this.$modal.msgError('请先选择商品')
					return false;
				}
				for (let key in this.form.goods) {
					if (
						this.form.goods[key].quantity == '' ||
						this.form.goods[key].unitPrice == '' ||
						this.form.goods[key].numberOfShippingBoxes == ''
					) {
						this.$modal.msgError('销售单价/数量/箱数量不能为空')
						return false;
					}
				}
				// 计算提成
				this.getFnRoyalties(1)
			},
			//计算提成
			getFnRoyalties(num) {
				let data = {
					list: this.form.goods.concat(this.form.gift),
					areaCode: this.form.areaCode, //地区编码
					logisticsId: this.form.logisticsId, //物流id
					orderTotalAmount:this.form.orderTotalAmount
				}
				fnRoyalties(data).then(res => {
					if (num == 1) {
						this.revenue = res.data.commissionAmount
						this.dividePrice = res.data.premiumAmount
						this.isCanGift = res.data.isCanGift
						// if (res.data.isCanGift == false) {
						// 	this.$modal.msgError('暂无赠品')
						// 	this.form.gift = []
						// 	return false;
						// }
					} else {
						this.isCanGiftFunc = res.data.isCanGift
					}
				})
			},

			//选中赠品
			selectGift(e) {
				this.getGoodsGroupList(e, 1)
			},
			// 提交订单
			orderSubmit(formName) {
				console.log(this.form,'form=====')
				
				let goodsArr = this.form.goods.concat(this.form.gift)
				let goodsArr1 = this.form.goods
				this.form.shippingAddress = this.form.addressName + ' ' + this.form.shippingAddress1
				for (let key in goodsArr1) {
					if (goodsArr[key].unitPrice == '') {
						this.$message({
							message: '请填写商品销售单价',
							type: 'error'
						});
						return false;
					} 
					// else if (goodsArr[key].unitPrice * 1 == 0) {
					// 	this.$message({
					// 		message: '请输入销售单价',
					// 		type: 'error'
					// 	});
					// 	return false;
					// } 
				}
				// 判断售价是否大于出厂价
				for (let key in goodsArr) {
					if (goodsArr[key].factoryPrice == '') {
						this.$message({
							message: '请填写商品数量',
							type: 'error'
						});
						return false;
					}
				}
				
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.form.commodityList = this.form.goods.concat(this.form.gift)
						let data = {
							list: this.form.goods.concat(this.form.gift),
							areaCode: this.form.areaCode, //地区编码
							logisticsId: this.form.logisticsId, //物流id
							orderTotalAmount:this.form.orderTotalAmount
						}
						let loading = this.$loading({
							lock:true,
							text:'提交中，请稍等',
							background:'rgba(0,0,0,0.5)'
						 })
						 // 新创建提交 || 草稿提交
						if (this.form.id == '' || this.form.orderStatus == '1001') {
							//新建
							fnRoyalties(data).then(res => {
								let isCanGiftFunc = res.data.isCanGift
								if (this.form.gift.length > 0 && !isCanGiftFunc) {
									loading.close()
									//有赠品，赠品不满足赠送
									this.$modal.msgError('毛利率过低，请调整赠品！')
									return false;
								} else if (this.form.gift.length > 0 && isCanGiftFunc) {
									// alert('pass1')
									// return false;
									// 有赠品，赠品满足赠送
									orderAdd(this.form).then(res => {
										if (res.code == 200) {
											this.$modal.msgSuccess('提交成功')
											this.$emit('getList')
											this.dialogVisible = false
											this.reset()
										}
									})
								} else {
									// alert('pass2')
									// return false;
									//无赠品，直接提交
									orderAdd(this.form).then(res => {
										if (res.code == 200) {
											this.$modal.msgSuccess('提交成功')
											this.$emit('getList')
											this.dialogVisible = false
											this.reset()
										}
									})
								}
							})
						} else {
							//编辑
							fnRoyalties(data).then(res => {
								let isCanGiftFunc = res.data.isCanGift
								if (this.form.gift.length > 0 && !isCanGiftFunc) {
									//有赠品，赠品不满足赠送
									this.$modal.msgError('毛利率过低，请调整赠品！')
									loading.close()
									return false;
								} else if (this.form.gift.length > 0 && isCanGiftFunc) {
									// 有赠品，赠品满足赠送
									orderEdit(this.form).then(res => {
										if (res.code == 200) {
											this.$modal.msgSuccess('编辑成功')
											this.$emit('getList')
											this.dialogVisible = false
										}
									})
								} else {
									//无赠品，直接提交
									orderEdit(this.form).then(res => {
										if (res.code == 200) {
											this.$modal.msgSuccess('编辑成功')
											this.$emit('getList')
											this.dialogVisible = false
										}
									})
								}
							})
						}
						setTimeout(()=>{
							loading.close()
						},1500)
					}
				})
			},
			//保存草稿
			saveOrderDemo(formName) {
				this.form.commodityList = this.form.goods.concat(this.form.gift)
				this.form.shippingAddress = this.form.addressName + ' '+ this.form.shippingAddress1
				this.$refs[formName].validate((valid) => {
					if (valid) {
						orderDemo(this.form).then(res => {
							this.$modal.msgSuccess('已保存草稿')
							this.$emit('getList')
							this.dialogVisible = false
							this.$forceUpdate()
						})
					}
				})		
			},
			reset() {
				
				this.form = {
					id: '',
					orderSource: '', //订单来源
					customerId: '', //客户id
					customerName: '', //客户姓名
					businessManagerId: '', //业务经理id
					businessManager: '', //业务经理
					paymentType: '1002', //付款类型
					paymentMethod: '', //付款方式
					differenceAmount:'',//订单差值
					remark: '', //备注
					paymentUrl: '', //付款截图url
					recipient: '', //收货人
					recipientPhone: '', //收货人手机号
					shippingAddress:'',
					shippingAddress1: '', //收货地址
					logisticsId: '', //物流id
					logistics: '', //物流名称
					documentType: '1001', //文档单据类型
					orderTotalAmount: '', //订单总金额
					priceType: '1001', //默认出厂价bus_goods_price_type 字典
					goods: [], //商品
					gift: [], //赠品
					areaCode: '', //省
					commodityList: [{
						type: '', //类型（0=商品，1=赠品）
						commodityId: '', //商品id
						commoditySpecification: '', //商品规格
						factoryPrice: '', //出厂价
						unitPrice: '', //销售单价（元）
						quantity: '1', //数量
						subtotal: '', //小计
						classifyId: '', //分类id
						commodityType: '', //产品类型正常品，试验品促销品
						commodityNumber: '', //商品编码
						productId: '', //关联产品id
						specificationId: '', //关联规格ID
						commodityName: '', //商品名称
						commodityCode: '', //商品Code码
						minUnit: '', //最小单位
						caseQuantity: '', //整件数量
						unitContent: '', //单位含量
						contentUnit: '', //含量单位（数据字典）
						mainImageUrl: '', //商品主图URL
						onlineUnitPrice: '', //线上拆箱单价
						caseUnitPrice: '', //整件单价
						tonPrice: '', //吨价
						numberOfShippingBoxes: '', //箱数量
						commissionRatio:'',//提成比率
					}] //订单商品信息
				}
				this.revenue = 0 //预估收益
				this.dividePrice = 0 //溢价分成
				this.hjPrice = 0
				this.addressNode = []
				return true
			}
		}
	}
</script>

<style>
	.alwaysVisibleClass {
		display: block !important;
	}

	.el-form--default.el-form--label-top .el-form-item .el-form-item__label {
		margin-bottom: 0;
		line-height: 36px;
	}

	.avatar-uploader .el-upload {
		background: #F7F8FA;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
		width: 110px;
		height: 110px;
		text-align: center;
		line-height: 22px;
		color: #8c939d;
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		text-align: center;
	}
</style>